[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import { isIPageInfoForEntity, isPopulated } from '@growi/core';
  4. import type {
  5. GroupType,
  6. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  7. } from '@growi/core';
  8. import {
  9. isClient, pagePathUtils, pathUtils,
  10. } from '@growi/core/dist/utils';
  11. import ExtensibleCustomError from 'extensible-custom-error';
  12. import type {
  13. GetServerSideProps, GetServerSidePropsContext,
  14. } from 'next';
  15. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  16. import dynamic from 'next/dynamic';
  17. import Head from 'next/head';
  18. import { useRouter } from 'next/router';
  19. import superjson from 'superjson';
  20. import { useEditorModeClassName } from '~/client/services/layout';
  21. import { PageView } from '~/components/Page/PageView';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import type { CrowiRequest } from '~/interfaces/crowi-request';
  24. import type { EditorConfig } from '~/interfaces/editor-settings';
  25. import type { IPageGrantData } from '~/interfaces/page';
  26. import type { RendererConfig } from '~/interfaces/services/renderer';
  27. import type { PageModel, PageDocument } from '~/server/models/page';
  28. import type { PageRedirectModel } from '~/server/models/page-redirect';
  29. import {
  30. useCurrentUser,
  31. useIsForbidden, useIsSharedUser,
  32. useIsEnabledStaleNotification, useIsIdenticalPath,
  33. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  34. useDefaultIndentSize, useIsIndentSizeForced,
  35. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  36. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  37. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  38. useEditorConfig, useIsAllReplyShown, useIsUploadAllFileAllowed, useIsUploadEnabled, useIsContainerFluid, useIsNotCreatable,
  39. } from '~/stores/context';
  40. import { useEditingMarkdown } from '~/stores/editor';
  41. import {
  42. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  43. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  44. } from '~/stores/page';
  45. import { useRedirectFrom } from '~/stores/page-redirect';
  46. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  47. import { useSelectedGrant } from '~/stores/ui';
  48. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  49. import loggerFactory from '~/utils/logger';
  50. import { BasicLayout } from '../components/Layout/BasicLayout';
  51. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  52. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  53. import type { NextPageWithLayout } from './_app.page';
  54. import type { CommonProps } from './utils/commons';
  55. import {
  56. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR,
  57. } from './utils/commons';
  58. declare global {
  59. // eslint-disable-next-line vars-on-top, no-var
  60. var globalEmitter: EventEmitter;
  61. }
  62. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  63. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  64. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  65. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  66. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  67. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  68. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  69. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  70. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  71. const TagEditModal = dynamic(() => import('../components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  72. const logger = loggerFactory('growi:pages:all');
  73. const {
  74. isPermalink: _isPermalink, isCreatablePage,
  75. } = pagePathUtils;
  76. const { removeHeadingSlash } = pathUtils;
  77. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  78. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  79. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  80. {
  81. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  82. return v?.data != null
  83. && v?.data.toObject != null
  84. && v?.meta != null
  85. && isIPageInfoForEntity(v.meta);
  86. },
  87. serialize: (v) => {
  88. return {
  89. data: superjson.stringify(v.data.toObject()),
  90. meta: superjson.stringify(v.meta),
  91. };
  92. },
  93. deserialize: (v) => {
  94. return {
  95. data: superjson.parse(v.data),
  96. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  97. };
  98. },
  99. },
  100. 'IPageToShowRevisionWithMetaTransformer',
  101. );
  102. // GrowiContextualSubNavigation for NOT shared page
  103. type GrowiContextualSubNavigationProps = {
  104. isLinkSharingDisabled: boolean,
  105. }
  106. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  107. const { isLinkSharingDisabled } = props;
  108. const { data: currentPage } = useSWRxCurrentPage();
  109. return (
  110. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  111. );
  112. };
  113. type Props = CommonProps & {
  114. pageWithMeta: IPageToShowRevisionWithMeta | null,
  115. // pageUser?: any,
  116. redirectFrom?: string;
  117. // shareLinkId?: string;
  118. isLatestRevision?: boolean,
  119. isIdenticalPathPage?: boolean,
  120. isForbidden: boolean,
  121. isNotFound: boolean,
  122. isNotCreatable: boolean,
  123. // isAbleToDeleteCompletely: boolean,
  124. templateTagData?: string[],
  125. templateBodyData?: string,
  126. isSearchServiceConfigured: boolean,
  127. isSearchServiceReachable: boolean,
  128. isSearchScopeChildrenAsDefault: boolean,
  129. isEnabledMarp: boolean,
  130. isSlackConfigured: boolean,
  131. // isMailerSetup: boolean,
  132. isAclEnabled: boolean,
  133. // hasSlackConfig: boolean,
  134. drawioUri: string | null,
  135. noCdn: string,
  136. // highlightJsStyle: string,
  137. isAllReplyShown: boolean,
  138. isContainerFluid: boolean,
  139. editorConfig: EditorConfig,
  140. isEnabledStaleNotification: boolean,
  141. isEnabledAttachTitleHeader: boolean,
  142. // isEnabledLinebreaks: boolean,
  143. // isEnabledLinebreaksInComments: boolean,
  144. adminPreferredIndentSize: number,
  145. isIndentSizeForced: boolean,
  146. disableLinkSharing: boolean,
  147. skipSSR: boolean,
  148. ssrMaxRevisionBodyLength: number,
  149. grantData?: IPageGrantData,
  150. rendererConfig: RendererConfig,
  151. };
  152. const Page: NextPageWithLayout<Props> = (props: Props) => {
  153. // register global EventEmitter
  154. if (isClient() && window.globalEmitter == null) {
  155. window.globalEmitter = new EventEmitter();
  156. }
  157. const router = useRouter();
  158. useCurrentUser(props.currentUser ?? null);
  159. // commons
  160. useEditorConfig(props.editorConfig);
  161. useCsrfToken(props.csrfToken);
  162. useGrowiCloudUri(props.growiCloudUri);
  163. // page
  164. useIsContainerFluid(props.isContainerFluid);
  165. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  166. useIsForbidden(props.isForbidden);
  167. useIsNotCreatable(props.isNotCreatable);
  168. useRedirectFrom(props.redirectFrom ?? null);
  169. useIsSharedUser(false); // this page cann't be routed for '/share'
  170. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  171. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  172. useIsSearchPage(false);
  173. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  174. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  175. useIsSearchServiceReachable(props.isSearchServiceReachable);
  176. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  177. useIsSlackConfigured(props.isSlackConfigured);
  178. // useIsMailerSetup(props.isMailerSetup);
  179. useIsAclEnabled(props.isAclEnabled);
  180. // useHasSlackConfig(props.hasSlackConfig);
  181. // useNoCdn(props.noCdn);
  182. useDefaultIndentSize(props.adminPreferredIndentSize);
  183. useIsIndentSizeForced(props.isIndentSizeForced);
  184. useDisableLinkSharing(props.disableLinkSharing);
  185. useRendererConfig(props.rendererConfig);
  186. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  187. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  188. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  189. useIsAllReplyShown(props.isAllReplyShown);
  190. useIsUploadAllFileAllowed(props.editorConfig.upload.isUploadAllFileAllowed);
  191. useIsUploadEnabled(props.editorConfig.upload.isUploadEnabled);
  192. const { pageWithMeta } = props;
  193. const pageId = pageWithMeta?.data._id;
  194. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  195. const revisionBody = pageWithMeta?.data.revision?.body;
  196. useCurrentPathname(props.currentPathname);
  197. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  198. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  199. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  200. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  201. const { mutate: mutateIsNotFound } = useIsNotFound();
  202. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  203. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  204. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  205. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  206. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  207. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  208. useSetupGlobalSocket();
  209. useSetupGlobalSocketForPage(pageId);
  210. // Store initial data (When revisionBody is not SSR)
  211. useEffect(() => {
  212. if (!props.skipSSR) {
  213. return;
  214. }
  215. if (currentPageId != null && !props.isNotFound) {
  216. const mutatePageData = async() => {
  217. const pageData = await mutateCurrentPage();
  218. mutateEditingMarkdown(pageData?.revision.body);
  219. };
  220. // If skipSSR is true, use the API to retrieve page data.
  221. // Because pageWIthMeta does not contain revision.body
  222. mutatePageData();
  223. }
  224. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  225. // sync grant data
  226. useEffect(() => {
  227. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  228. mutateSelectedGrant(grantDataToApply);
  229. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  230. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  231. useEffect(() => {
  232. const decodedURI = decodeURI(window.location.pathname);
  233. if (isClient() && decodedURI !== props.currentPathname) {
  234. const { search, hash } = window.location;
  235. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  236. }
  237. }, [props.currentPathname, router]);
  238. // initialize mutateEditingMarkdown only once per page
  239. // need to include useCurrentPathname not useCurrentPagePath
  240. useEffect(() => {
  241. if (props.currentPathname != null) {
  242. mutateEditingMarkdown(revisionBody);
  243. }
  244. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  245. useEffect(() => {
  246. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  247. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  248. useEffect(() => {
  249. mutateCurrentPageId(pageId ?? null);
  250. }, [mutateCurrentPageId, pageId]);
  251. useEffect(() => {
  252. mutateIsNotFound(props.isNotFound);
  253. }, [mutateIsNotFound, props.isNotFound]);
  254. useEffect(() => {
  255. mutateIsLatestRevision(props.isLatestRevision);
  256. }, [mutateIsLatestRevision, props.isLatestRevision]);
  257. useEffect(() => {
  258. mutateTemplateTagData(props.templateTagData);
  259. }, [props.templateTagData, mutateTemplateTagData]);
  260. useEffect(() => {
  261. mutateTemplateBodyData(props.templateBodyData);
  262. }, [props.templateBodyData, mutateTemplateBodyData]);
  263. const title = generateCustomTitleForPage(props, pagePath);
  264. return (
  265. <>
  266. <Head>
  267. <title>{title}</title>
  268. </Head>
  269. <div className="dynamic-layout-root justify-content-between">
  270. <nav className="sticky-top">
  271. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  272. </nav>
  273. <DisplaySwitcher
  274. pageView={(
  275. <PageView
  276. pagePath={pagePath}
  277. initialPage={pageWithMeta?.data}
  278. rendererConfig={props.rendererConfig}
  279. />
  280. )}
  281. />
  282. <PageStatusAlert />
  283. </div>
  284. </>
  285. );
  286. };
  287. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  288. const editorModeClassName = useEditorModeClassName();
  289. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  290. };
  291. type LayoutProps = Props & {
  292. children?: ReactNode
  293. }
  294. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  295. // init sidebar config with UserUISettings and sidebarConfig
  296. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  297. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  298. };
  299. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  300. return (
  301. <>
  302. <GrowiPluginsActivator />
  303. <DrawioViewerScript />
  304. <Layout {...page.props}>
  305. {page}
  306. </Layout>
  307. <UnsavedAlertDialog />
  308. <DescendantsPageListModal />
  309. <DrawioModal />
  310. <HandsontableModal />
  311. <QuestionnaireModalManager />
  312. <TemplateModal />
  313. <LinkEditModal />
  314. <TagEditModal />
  315. </>
  316. );
  317. };
  318. function getPageIdFromPathname(currentPathname: string): string | null {
  319. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  320. }
  321. class MultiplePagesHitsError extends ExtensibleCustomError {
  322. pagePath: string;
  323. constructor(pagePath: string) {
  324. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  325. this.pagePath = pagePath;
  326. }
  327. }
  328. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  329. const { model: mongooseModel } = await import('mongoose');
  330. const req: CrowiRequest = context.req as CrowiRequest;
  331. const { crowi } = req;
  332. const { revisionId } = req.query;
  333. const Page = crowi.model('Page') as PageModel;
  334. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  335. const { pageService, configManager, pageGrantService } = crowi;
  336. let currentPathname = props.currentPathname;
  337. const pageId = getPageIdFromPathname(currentPathname);
  338. const isPermalink = _isPermalink(currentPathname);
  339. const { user } = req;
  340. if (!isPermalink) {
  341. // check redirects
  342. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  343. if (chains != null) {
  344. // overwrite currentPathname
  345. currentPathname = chains.end.toPath;
  346. props.currentPathname = currentPathname;
  347. // set redirectFrom
  348. props.redirectFrom = chains.start.fromPath;
  349. }
  350. // check whether the specified page path hits to multiple pages
  351. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  352. if (count > 1) {
  353. throw new MultiplePagesHitsError(currentPathname);
  354. }
  355. }
  356. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  357. const page = pageWithMeta?.data as unknown as PageDocument;
  358. // add user to seen users
  359. if (page != null && user != null) {
  360. await page.seen(user);
  361. }
  362. // populate & check if the revision is latest
  363. if (page != null) {
  364. page.initLatestRevisionField(revisionId);
  365. props.isLatestRevision = page.isLatestRevision();
  366. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  367. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  368. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  369. }
  370. if (page == null && user != null) {
  371. const templateData = await Page.findTemplate(props.currentPathname);
  372. if (templateData != null) {
  373. props.templateTagData = templateData.templateTags as string[];
  374. props.templateBodyData = templateData.templateBody as string;
  375. }
  376. // apply parent page grant, without groups that user isn't related to
  377. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  378. if (ancestor != null) {
  379. ancestor.populate('grantedGroups.item');
  380. const userRelatedGrantedGroups = (await pageGrantService.getUserRelatedGrantedGroups(ancestor, user)).map((group) => {
  381. if (isPopulated(group.item)) {
  382. return {
  383. id: group.item._id,
  384. name: group.item.name,
  385. type: group.type,
  386. };
  387. }
  388. return null;
  389. }).filter((info): info is NonNullable<{id: string, name: string, type: GroupType}> => info != null);
  390. props.grantData = {
  391. grant: ancestor.grant,
  392. userRelatedGrantedGroups,
  393. };
  394. }
  395. }
  396. props.pageWithMeta = pageWithMeta;
  397. }
  398. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  399. const req: CrowiRequest = context.req as CrowiRequest;
  400. const { crowi } = req;
  401. const Page = crowi.model('Page') as PageModel;
  402. const { currentPathname } = props;
  403. const pageId = getPageIdFromPathname(currentPathname);
  404. const isPermalink = _isPermalink(currentPathname);
  405. const page = props.pageWithMeta?.data;
  406. if (props.isIdenticalPathPage) {
  407. props.isNotCreatable = true;
  408. }
  409. else if (page == null) {
  410. props.isNotFound = true;
  411. props.isNotCreatable = !isCreatablePage(currentPathname);
  412. // check the page is forbidden or just does not exist.
  413. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  414. props.isForbidden = count > 0;
  415. }
  416. else {
  417. props.isNotFound = page.isEmpty;
  418. props.isNotCreatable = false;
  419. props.isForbidden = false;
  420. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  421. if (isPermalink && page.isEmpty) {
  422. props.currentPathname = page.path;
  423. }
  424. // /path/to/page ==> /62a88db47fed8b2d94f30000
  425. if (!isPermalink && !page.isEmpty) {
  426. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  427. if (!isToppage) {
  428. props.currentPathname = `/${page._id}`;
  429. }
  430. }
  431. }
  432. }
  433. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  434. // const req: CrowiRequest = context.req as CrowiRequest;
  435. // const { crowi } = req;
  436. // const UserModel = crowi.model('User');
  437. // if (isUserPage(props.currentPagePath)) {
  438. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  439. // if (user != null) {
  440. // props.pageUser = JSON.stringify(user.toObject());
  441. // }
  442. // }
  443. // }
  444. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  445. const req: CrowiRequest = context.req as CrowiRequest;
  446. const { crowi } = req;
  447. const {
  448. searchService, configManager, aclService,
  449. } = crowi;
  450. props.isSearchServiceConfigured = searchService.isConfigured;
  451. props.isSearchServiceReachable = searchService.isReachable;
  452. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  453. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  454. // props.isMailerSetup = mailService.isMailerSetup;
  455. props.isAclEnabled = aclService.isAclEnabled();
  456. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  457. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  458. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  459. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  460. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  461. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  462. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  463. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  464. props.editorConfig = {
  465. upload: {
  466. isUploadAllFileAllowed: crowi.fileUploadService.getFileUploadEnabled(),
  467. isUploadEnabled: crowi.fileUploadService.getIsUploadable(),
  468. },
  469. };
  470. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  471. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  472. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  473. props.rendererConfig = {
  474. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  475. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  476. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  477. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  478. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  479. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  480. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  481. // XSS Options
  482. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  483. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  484. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  485. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  486. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  487. };
  488. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  489. }
  490. /**
  491. * for Server Side Translations
  492. * @param context
  493. * @param props
  494. * @param namespacesRequired
  495. */
  496. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  497. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  498. props._nextI18Next = nextI18NextConfig._nextI18Next;
  499. }
  500. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  501. const req = context.req as CrowiRequest;
  502. const { user } = req;
  503. const result = await getServerSideCommonProps(context);
  504. // check for presence
  505. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  506. if (!('props' in result)) {
  507. throw new Error('invalid getSSP result');
  508. }
  509. const props: Props = result.props as Props;
  510. if (props.redirectDestination != null) {
  511. return {
  512. redirect: {
  513. permanent: false,
  514. destination: props.redirectDestination,
  515. },
  516. };
  517. }
  518. if (user != null) {
  519. props.currentUser = user.toObject();
  520. }
  521. try {
  522. await injectPageData(context, props);
  523. }
  524. catch (err) {
  525. if (err instanceof MultiplePagesHitsError) {
  526. props.isIdenticalPathPage = true;
  527. }
  528. else {
  529. throw err;
  530. }
  531. }
  532. await injectRoutingInformation(context, props);
  533. injectServerConfigurations(context, props);
  534. await injectNextI18NextConfigurations(context, props, ['translation']);
  535. return {
  536. props,
  537. };
  538. };
  539. export default Page;